package com.geek.novel.utils

import android.text.TextUtils
import com.geek.novel.error.ValidateException
import java.util.regex.Pattern

object ValidateUtil {

    fun validateNotEmpty(value: String?, name: String, error: String?=null){
        if(TextUtils.isEmpty(value)){
            var message = error
            if(TextUtils.isEmpty(message)){
                message = "请输入${name}！"
            }
            throw ValidateException(message!!)
        }
    }

    fun validateEmail(value: String?, name: String, empty: Boolean=false){
        if(!empty){
            validateNotEmpty(value, name)
        }
        if(!TextUtils.isEmpty(value)){
            if (value!!.length > 100) {
                throw ValidateException("邮箱长度过长！请检查后重试")
            }
            val regex = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"
            this.match(value, name, regex)
        }
    }

    fun validatePhone(value: String?, name: String, empty: Boolean=false){
        if(!empty){
            validateNotEmpty(value, name)
        }
        if(!TextUtils.isEmpty(value)){
            val regex = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$"
            this.match(value, name, regex)
        }
    }

    fun validatePassword(value: String?, name: String, empty: Boolean=false){
        if(!empty){
            validateNotEmpty(value, name)
        }
        if(!TextUtils.isEmpty(value)){
//            val regex = "^[A-Z][A-Za-z0-9_\\.@\\!\\#\\$]{5,19}$"
            val regex = "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[\\(\\)])+$)([^(0-9a-zA-Z)]|[\\(\\)]|[a-z]|[A-Z]|[0-9]){6,20}$"
            this.match(value, name, regex, "请输入包含大小写字母/数字/符号任意两者组合的6-20位密码！")
        }
    }

    private fun match(value: String?, name: String, regex: String, error: String?=null){
        val pattern = Pattern.compile(regex)
        val matcher = pattern.matcher(value)
        if(!matcher.matches()){
            var message = error
            if(TextUtils.isEmpty(message)){
                message = "${name}格式错误！"
            }
            throw ValidateException(message!!)
        }
    }

}